/***************************************************
> Copyright (C) 2024 ==FLY== All rights reserved.
> File Name: file.c
> Author: fly
> Mail:2243920918@qq.com 
> Created Time: 2024年12月10日 星期二 10时16分50秒
***************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

//cat函数实现
int mycat(const char *filename);

//cp函数实现
int mycp(const char *newfilename, const char *filename);

int main(int argc, const char* argv[])
{
    int num;
    num = mycat("cat.txt");
    if(num)
    {
        printf("文件读取成功！\n");
    }
    else
    {
        printf("文件读取失败！\n");
    }

    printf("\n");

    num = mycp(argv[1], argv[2]);
    if(num)
    {
         printf("文件复制成功！\n");
    }
    else
    {
        printf("文件复制失败！\n");
    }

    return 0;
}


//cat函数
int mycat(const char *filename)
{
    int pf;
    char ch[10] = {0};

    pf = open(filename, O_RDONLY);
    if(pf == -1)
    {
        printf("文件打开失败！");
        return 0;
    }

    int len = 0;
    while((len = read(pf, ch, sizeof(ch) - 1)) != 0)
    {
        if(len == -1)
        {
            printf("读取数据错误！\n");
            return 0;
        }
        printf("%s", ch);
    }

    close(pf);

    return 1;
}

//cp函数
int mycp(const char *newfilename, const char *filename)
{
    int rpf = 0;
    int wpf = 0;
    char str[10] = {0};

    rpf = open(filename, O_RDONLY);
    if(rpf == -1)
    {
        printf("原文件打开失败！\n");
        return 0;
    }

    wpf = open(newfilename, O_WRONLY | O_CREAT, 0700);
    if(wpf == -1)
    {
        close(rpf);
        printf("复制文件打开失败！\n");
        return 0;
    }

    int len = 0;
    while((len = read(rpf, str, sizeof(str))) != 0)
    {
        if(len == -1)
        {
            printf("读取数据错误！\n");
            return 0;
        }
        write(wpf, str, len);
    }

    close(rpf);
    close(wpf);

    return 1;
}
